package com.sea.wechat.util;

import org.xml.sax.InputSource;
import org.xml.sax.XMLReader;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.Source;
import javax.xml.transform.sax.SAXSource;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;



public class JaxbUtil {
    /**
     * JavaBean转换成xml
     * 默认编码UTF-8
     * @param obj
     * @param
     * @return
     */
    public static String convertToXml(Object obj) {
        return convertToXml(obj, "UTF-8");
    }
 
    /**
     * JavaBean转换成xml
     * @param obj
     * @param encoding
     * @return
     */
    @SuppressWarnings("all")
	public static String convertToXml(Object obj, String encoding) {
        String result = null;
        try {
            JAXBContext context = JAXBContext.newInstance(obj.getClass());
            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
            marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);
            //去掉生成xml的默认报文头
            marshaller.setProperty(Marshaller.JAXB_FRAGMENT, true);
            ///转换所有的适配字符，包括xml实体字符&lt;和&gt
            marshaller.setProperty("com.sun.xml.bind.marshaller.CharacterEscapeHandler",
                    new com.sun.xml.bind.marshaller.CharacterEscapeHandler() {
                public void escape(char[] ch, int start,int length, boolean isAttVal,
                        Writer writer) throws IOException {
                    writer.write(ch, start, length);
                }
            });            
            
            StringWriter writer = new StringWriter();
            marshaller.marshal(obj, writer);
            result = writer.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
 
        return result;
    }
 
    /**
     * xml转换成JavaBean
     * @param xml
     * @param c
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T> T converyToJavaBean(String xml, Class<T> c) {
        T t = null;
        try {
            JAXBContext context = JAXBContext.newInstance(c);
            Unmarshaller unmarshaller = context.createUnmarshaller();
          
            StringReader reader = new StringReader(xml);  
            SAXParserFactory sax = SAXParserFactory.newInstance();  
            sax.setNamespaceAware(false);  
            XMLReader xmlReader = sax.newSAXParser().getXMLReader();  
            Source source = new SAXSource(xmlReader, new InputSource(reader));            
            
            t = (T) unmarshaller.unmarshal(source);
        } catch (Exception e) {
            e.printStackTrace();
        }
 
        return t;
    }
}
